<template>
  <div class="create-order-container">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>创建预订单</h3>
          <el-button @click="router.back()">返回</el-button>
        </div>
      </template>

      <el-steps :active="active" finish-status="success" class="mb-4">
        <el-step title="确认预订信息" />
        <el-step title="提交订单" />
        <el-step title="支付" />
      </el-steps>

      <!-- 第一步：确认预订信息 -->
      <div v-if="active === 0">
        <el-descriptions title="会议室信息" :column="2" border>
          <el-descriptions-item label="会议室名称">{{ roomInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="会议室类型">{{ roomInfo.type === 'classroom' ? '教室型' : '圆桌型' }}</el-descriptions-item>
          <el-descriptions-item label="座位数">{{ roomInfo.capacity }}</el-descriptions-item>
          <el-descriptions-item label="设备支持">
            <template v-if="roomInfo.roomEquipments && roomInfo.roomEquipments.length">
                <el-tag 
                  v-for="equipment in roomInfo.roomEquipments" 
                  :key="equipment.equipmentId"  
                  style="margin-right: 5px; margin-bottom: 5px"
                >
                  {{ equipment.equipmentName }}
                </el-tag>
            </template>
            <span v-else>-</span> 
          </el-descriptions-item>
          <el-descriptions-item label="每小时价格">¥{{ roomInfo.price }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="预订信息" :column="2" border class="mt-4">
          <el-descriptions-item label="使用日期">{{ formatDate(route.query.date) }}</el-descriptions-item>
          <el-descriptions-item label="使用时间">{{ route.query.startTime }} - {{ route.query.endTime }}</el-descriptions-item>
          <el-descriptions-item label="使用时长">{{ useHours }}小时</el-descriptions-item>
          <el-descriptions-item label="总价">¥{{ totalPrice }}</el-descriptions-item>
        </el-descriptions>

        <div class="action-bar">
          <el-button type="primary" @click="nextStep">确认信息</el-button>
        </div>
      </div>

      <!-- 第二步：提交订单 -->
      <div v-if="active === 1">
        <el-result
          icon="success"
          title="预订信息确认完成"
          sub-title="请确认是否提交订单"
        >
          <template #extra>
            <el-button type="primary" @click="submitOrder">提交订单</el-button>
            <el-button @click="active = 0">返回修改</el-button>
          </template>
        </el-result>
      </div>

      <!-- 第三步：支付 -->
      <div v-if="active === 2">
        <el-result
          icon="success"
          title="订单创建成功"
          :sub-title="'订单号：' + currentReservationId">
        >
          <template #extra>
            <el-button type="primary" @click="handlePay">立即支付</el-button>
            <el-button @click="router.push('/customer/orderList')">查看订单</el-button>
          </template>
        </el-result>
      </div>
    </el-card>

    <!-- 支付对话框 -->
    <el-dialog
      v-model="payDialogVisible"
      title="订单支付"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-result
        icon="info"
        title="待支付"
        sub-title="请选择支付方式完成支付"
      >
        <template #extra>
          <div class="pay-amount">支付金额：<span class="price">¥{{ totalPrice }}</span></div>
          <el-radio-group v-model="payMethod" class="pay-methods">
            <el-radio label="wechat">支付宝支付</el-radio>
          </el-radio-group>
          <el-button type="primary" @click="confirmPay" :loading="paying">确认支付</el-button>
        </template>
      </el-result>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { getSessionStorage } from '../../utils/common'
import {createOrder, payOrder} from '../../api/orderApi'
import { User } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const active = ref(0)
const payDialogVisible = ref(false)
const payMethod = ref('wechat')
const paying = ref(false)
const currentReservationId = ref(0)

// 使用路由参数初始化会议室信息
const roomInfo = ref({
  id: route.query.roomId,
  name:route.query.name,
  type: route.query.type,
  capacity: route.query.maxCapacity,
  price: route.query.hourlyRentalPrice,
  roomEquipments: getSessionStorage("roomEquipments")
})

onMounted(() => {
})

const useHours = computed(() => {
  if (!route.query.startTime || !route.query.endTime) return 0
  const start = dayjs(`2000-01-01 ${route.query.startTime}`)
  const end = dayjs(`2000-01-01 ${route.query.endTime}`)
  return end.diff(start, 'hour')
})

const totalPrice = computed(() => {
  return roomInfo.value.price * useHours.value
})

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

const nextStep = () => {
  active.value++
}

async function submitOrder() {
  const params = {
    roomId: Number(route.query.roomId),
    userId: Number(getSessionStorage("customerId")),
    date: route.query.date,
    startTime: route.query.startTime,
    endTime: route.query.endTime,
    perosonNum: Number(route.query.maxCapacity)
  }
    try {
    const response = await createOrder(params)
    if(response.flag) {
      ElMessage.success('创建订单成功')
      currentReservationId.value = response.result      
      active.value++
    } else {
      ElMessage.error(response.reason || '请求失败')
    }
  } catch(error) {
    ElMessage.error('网络错误：' + error.message)
    console.error("创建订单错误:", error)
  }
}

const handlePay = () => {
  payDialogVisible.value = true
}

async function confirmPay(){
  paying.value = true
  // TODO: 调用支付接口
  try{
    const params = {
      reservationId: currentReservationId.value
    }
    const response = await payOrder(params)
    const blob = new Blob([response],{type:"text/html"});
    const url = URL.createObjectURL(blob)
    window.open(url,'_self')
    ElMessage.success('支付成功')
    // router.push('/customer/orderList')
    
    // if(response.flag){
    //   paying.value = false
    //   payDialogVisible.value = false
    //   ElMessage.success('支付成功')
    //   router.push('/customer/orderList')
    // }else{
    //   paying.value = false
    //   ElMessage.error(response.reason || '请求失败')
    // }
  }catch(error){
    ElMessage.error('网络错误：' + error.message)
    console.error("支付订单错误:", error)
    router.push('/customer/roomList')
  }
}
</script>

<style scoped>
.create-order-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-4 {
  margin-bottom: 24px;
}

.mt-4 {
  margin-top: 24px;
}

.ml-1 {
  margin-left: 4px;
}

.action-bar {
  margin-top: 24px;
  text-align: center;
}

.pay-amount {
  font-size: 16px;
  margin-bottom: 16px;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.pay-methods {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 24px;
}
</style> 